<?php

namespace app\api\controller;

use app\admin\model\Comment as ModelComment;
use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\Calculation\Information\Value;
use think\Db;
use think\Exception;

class Comment extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];
    /**
     * 我的留言列表
     */
    public function getCommentList()
    {
        // $user_id = 2;
        $user_id = $this->auth->id;
        if (!$user_id) {
            $this->error('请登录');
        }
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 10);
        $type = $this->request->param('type/d', 0);
        if (!$type) {
            $this->error('请选择留言类别');
        }
        if ($type == 1) { // 我的留言
            $where1 = ['p.auth_id' => ['<>', $user_id]];
            $where2 = ['c.user_id' => $user_id];
        } else { // 收到的留言
            $where1 = ['p.auth_id' => $user_id];
            $where2 = ['c.user_id' => ['<>', $user_id]];
        }
        $data = ModelComment::alias('c')
            ->join('post_post p', 'c.post_id = p.id')
            ->where($where1)
            ->where($where2)
            ->where('c.pid', 0)
            ->order('c.createtime desc')
            ->field('c.id, c.post_id, c.content, c.images, c.createtime,c.pid,c.user_id')
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->each(function ($item) {
                $userinfo = Db::name('user')->where('id', $item['user_id'])->field('id,nickname,avatar')->find();
                $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
                $item['userinfo'] = $userinfo;
                if ($item['images'] == '') {
                    $item['images'] = [];
                } else {
                    $item['images'] = array_map(function ($v) {
                        return cdnurl($v, true);
                    }, explode(',', $item['images']));
                }
                $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
                // 查询该主留言的回复（pid=主留言ID）
                $replies = ModelComment::where('pid', $item['id'])
                    ->field('id, post_id, content, images, createtime, pid, user_id')
                    ->order('createtime asc') // 按时间升序排列（最早的回复在前）
                    ->select();

                // 处理回复数据
                $item['child'] = array_map(function ($reply) {
                    $cuserinfo = Db::name('user')->where('id', $reply['user_id'])->field('id,nickname,avatar')->find();
                    $cuserinfo['avatar'] = cdnurl($cuserinfo['avatar'], true);
                    $reply['userinfo'] = $cuserinfo;
                    if ($reply['images'] == '') {
                        $reply['images'] = [];
                    } else {
                        $reply['images'] = array_map(function ($v) {
                            return cdnurl($v, true);
                        }, explode(',', $reply['images']));
                    }
                    $reply['createtime_text'] = date('Y-m-d H:i:s', $reply['createtime']);
                    return $reply;
                }, $replies);
                return $item;
            });

        $this->success('获取成功', $data);
    }
    /**
     * 回复留言
     */
    public function replyComment()
    {
        $user_id = $this->auth->id;
        // $user_id = 2;
        if (!$user_id) {
            $this->error('请登录');
        }
        $pid = $this->request->param('id/d', 0);
        $post_id = Db::name('comment')->where('id', $pid)->value('post_id');
        if (!$post_id) {
            $this->error('参数错误');
        }
        $content = $this->request->param('content/s', '');
        $images = $this->request->param('images/s', '');
        if (!$content) {
            $this->error('内容不能为空');
        }
        $data = [
            'user_id' => $user_id,
            'pid' => $pid,
            'post_id' => $post_id,
            'content' => $content,
            'images' => $images,
            'createtime' => time(),
        ];
        Db::startTrans();
        try {
            $result = ModelComment::create($data, true);
            if ($result) {
                Db::commit();
                $this->success('回复成功');
            } else {
                throw new Exception('回复失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    /**
     * 删除留言
     */
    public function deleteComment()
    {
        $user_id = $this->auth->id;
        // $user_id = 2;
        if (!$user_id) {
            $this->error('请登录');
        }
        $id = $this->request->param('id/d', 0);
        $comment = ModelComment::where('id', $id)->find();
        if (!$comment) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            if ($comment['user_id'] == $user_id) {
                $result = $comment->delete();
                if ($result) {
                    Db::commit();
                    $this->success('删除成功');
                } else {
                    throw new Exception('删除失败');
                }
            } else {
                throw new Exception('无权限删除');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
